package com.homwee.factory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

//zcj 2018-10-31 import com.changhong.inface.net.NetworkSettingUtils;
//zcj 2018-10-31 import com.changhong.inface.net.wifi.WifiAccessPoint;

import com.homwee.factory.util.BTManager;

import com.homwee.factory.util.BarCodeUtils;
import com.homwee.tvap.common.ap.ComSettingManager;
import com.homwee.tvap.common.srvfunc.FactorySetting;
import com.homwee.factory.util.Contants;
import com.homwee.listMenu.util.ExtraAdapter;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.os.SystemProperties;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.graphics.Color;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.Intent;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.common.MtkTvFApiResultTypeBase;
import com.mediatek.twoworlds.factory.clientwrapper.MtkTvFApiInformationWrapper;
import com.mediatek.twoworlds.factory.common.MtkTvFApiPeripheralTypes.IicDevice;
import com.mediatek.twoworlds.factory.model.MtkTvFApiIicReadMode;
import com.mediatek.twoworlds.factory.MtkTvFApiPeripheral;

public class FactoryListInfoActivity extends Activity {
	public static final int USB_CHECK = 0;
	public static final int LAN_CHECK = 1;
	public static final int WIFI_CHECK = 2;
	public static final int BT_CHECK = 3;
	public static final int KEY_STATUS_CHECK = 4;
	public static final int EEPROM_STATUS_SHOW=5;
	public String[] ItemName = { "USB CHECK", "LAN CHECK", "WIFI CHECK",
			"BT CHECK" };
	public static Context mContext;
	private ListView mListView;
	private static ArrayList<String> mDatas = new ArrayList<String>();
	public final String TAG = "zcj";
	//zcj 2018-10-31 private NetworkSettingUtils mNetworkSettingUtils;

	private BTManager mBtManager;
	private BluetoothAdapter mBluetoothAdapter;
	MyAdapter adapter;
	public int bt_count = 0;
	public String lastDeviceName = "", lastLastDeviceName = "";;
        private int usbCount = 0;

	// private BluetoothListAdapter mSearchAdapter;
	public ComSettingManager mcomSettingManager;
	public FactorySetting factorySetting;

	//keystatus data
	private String[] names=null;
	private Object[] values=null;
	List<Map<String,Object>> listitem=new ArrayList<Map<String,Object>>();

	//keystatus listView adapter
	ExtraAdapter keyStatusAdapter=null;

	//val to check wifi and bt is OK
	int wifiCheckVal=0;
	int btCheckVal=0;

	//EepromKey
	private String KEY_EEPROM_PATH = "/vendor/cusdata/factory/eeprom/eeprom_key_setting_cus.ini";
	public static String readMACString="ff:ff:ff:ff:ff:ff";
	public static String readPid="00";
	public static enum EnumEepromKey {
		E_EepromKey_HDCP14,
		E_EepromKey_HDCP2,
		E_EepromKey_MAC,
		E_EepromKey_WIDEVINE,
		E_EepromKey_PLAYREADY30_BGROUPCERT,
		E_EepromKey_PLAYREADY30_ZGPRIV,
		//    E_EepromKey_KEYMASTER,
		E_EepromKey_NETFLIX50_KPEKPH,
		E_EepromKey_NETFLIX50_ESNID,
		E_EepromKey_HASHKEY,
		E_EepromKey_PROJECT_ID,
		E_EepromKey_DEVICE_ID,
		E_EepromKey_MMODE,
		E_EepromKey_AGINGMODE,
		E_EepromKey_CIPLUS,
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// LayoutInflater vi = (LayoutInflater)
		// this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// mRootLayout =
		// (RelativeLayout)vi.inflate(R.layout.menu_information_list,null);
		// setContentView(mRootLayout);
		mContext = this;
		mcomSettingManager=ComSettingManager.getInstance(this);
		factorySetting = mcomSettingManager.getFactory();
		int ID = getIntent().getIntExtra("CheckItem", USB_CHECK);

		try {
			initData(ID);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (ID == KEY_STATUS_CHECK || ID==EEPROM_STATUS_SHOW) {
			setContentView(R.layout.keystatus_information_list);
			Log.v("keyStatusAdapter", listitem.size() + "");
			keyStatusAdapter =new ExtraAdapter(listitem, getApplicationContext(),0);
			Log.v("keyStatusAdapter", keyStatusAdapter.toString());
			mListView=(ListView)findViewById(R.id.itemListViewKeyStatus);
			Log.v("keyStatusAdapter", mListView.toString());
			mListView.setAdapter(keyStatusAdapter);
		} else {
			setContentView(R.layout.menu_information_list);
			mListView = (ListView) findViewById(R.id.listInfoView);
			adapter = new MyAdapter(mContext, mDatas);
			mListView.setAdapter(adapter);
		}
		
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String mSelName = ((TextView) arg1).getText().toString();
				Log.v("tv", mSelName);

			}
		});

		//mListView.setSelector(R.drawable.menu_item_selector);
		mListView.setFocusable(false);
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		registerReceiver(receiver ,intentFilter);
		//mListView.setSelector(Color.parseColor("#00000000"));
		// mListView.dataChange();
		// initView();
		// mEditText =new EditText(this);
		// factory=factorySetting.getInstance(this);
	}

	private void initData(int ID) throws InterruptedException {

		mDatas.clear();

		switch (ID) {

		case USB_CHECK:
            //showVerTime();
			UsbCheck();
			LANCheck();
			WifiCheck();
			BTCheck();
			showCheckResult();
			break;

		case LAN_CHECK:
			LANCheck();
			break;

		case WIFI_CHECK:

			break;

		case BT_CHECK:
			BTCheck();
			break;

		case KEY_STATUS_CHECK:
			KeystatusCheck();
			break;

		case EEPROM_STATUS_SHOW:
			EepromStatusShow();
			break;

		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_3D_MODE:
			//zcj 2018-10-31 case KeyEvent.KEYCODE_CHMIR_INPUT_SOURCE:
		case KeyEvent.KEYCODE_SETTINGS:
		case KeyEvent.KEYCODE_MENU:
			this.finish();
			Log.v("KEYCODE_MENU", "KEYCODE_MENU=" + KeyEvent.KEYCODE_MENU);
			return true;

			//zcj 2018-10-31 case KeyEvent.KEYCODE_CHMIR_F11:

			//zcj 2018-10-31 this.finish();
			//zcj 2018-10-31return true;

		default:

			break;
		}
		return super.onKeyDown(keyCode, event);

	}

	protected void onStart() {
		super.onStart();
		// initBarCode();
	}

	private void UsbCheck() {
		String CheckResult = "No USB disk";
                usbCount = 0;
		ArrayList<String> mountPoints = new ArrayList<String>();
		mountPoints.clear();
		StorageManager storageManager = (StorageManager) getApplicationContext()
				.getApplicationContext().getSystemService(
						Context.STORAGE_SERVICE);
		 StorageVolume[] mStorageVolume = storageManager.getVolumeList();
		if (mStorageVolume.length <= 1) {
                        CheckResult = formatString("USB","0","");
			mDatas.add(CheckResult);
			//mDatas.add("No USB disk!");
			return;
		}

		for (int i = 0; i < mStorageVolume.length; i++) {
			Log.d(TAG,
					"StorageVolume " + i + " state= "
							+ mStorageVolume[i].getState());
			Log.d(TAG,
					"StorageVolume " + i + " path= "
							+ mStorageVolume[i].getPath());
			if (mStorageVolume[i].getState().equals(Environment.MEDIA_MOUNTED)
					&& mStorageVolume[i].getPath().startsWith("/storage/")
					&&(!mStorageVolume[i].getPath().startsWith("/storage/emulated/0")
			)) {
				mountPoints.add(mStorageVolume[i].getPath());
				Log.d(TAG, "StorageVolume " + i + " path1= "
						+ mStorageVolume[i].getPath());
				CheckResult = "USB" + i + "                                "
						+ "OK";
				//mDatas.add(CheckResult);
                                usbCount++;

			}
		}
                
                CheckResult = formatString("USB",usbCount+"", " ");
		mDatas.add(CheckResult);
                
                /*
		if (mDatas.size() < 1) {
			CheckResult = "USB not found,Check again!";
			mDatas.add(CheckResult);
		}
                */

	}

	private void LANCheck() throws InterruptedException {
		String CheckResult = null;
		

		Thread.sleep(300);

		
		if (factorySetting.isLanConnected()) {
			//CheckResult = "Ethernet" + "                        " + "Connected";
			CheckResult = formatString("Ethernet", "Connected"," ");
			mDatas.add(CheckResult);
			//CheckResult = "IP" + "                            "+ factorySetting.getIPAdress();
			CheckResult = formatString("IP", factorySetting.getIPAdress()," ");
			mDatas.add(CheckResult);
		} else {
			//CheckResult = "Ethernet" + "                        "+ "Disconnected";
			CheckResult = formatString("Ethernet", "Disconnected", " ");
			mDatas.add(CheckResult);
			//CheckResult = "IP" + "                             " + "NULL";
			CheckResult = formatString("IP", factorySetting.getIPAdress()," ");
			mDatas.add(CheckResult);

		}
		//CheckResult = "MAC" + "                      "+ factorySetting.getMAC();
		//CheckResult = formatString("MAC", factorySetting.getMAC()," ");
		CheckResult = formatString("MAC",BarCodeUtils.getMAC("eth0"),"");
		mDatas.add(CheckResult);
	}

	private void WifiCheck() {
		String CheckResult = null;
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
                int status = wifiManager.getWifiState();  
                if(status != WifiManager.WIFI_STATE_ENABLED){
                       wifiManager.setWifiEnabled(true);
                       try{
		           Thread.sleep(500);
                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                }
                
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		if (!(wifiInfo == null || wifiInfo.getMacAddress() == null))
		{
		    //String mac = wifiInfo.getFactoryMacAddress().trim().toUpperCase();
			//String mac = BarCodeUtils.getMAC("wlan0");
			String mac=BarCodeUtils.getDeviceMac(mContext);
		    mDatas.add(formatString("WIFI MAC",mac," "));
		}
                
        List<ScanResult> scanWifiList = wifiManager.getScanResults();
		List<ScanResult> wifiList = new ArrayList<>();
		if (scanWifiList != null && scanWifiList.size() > 0) {
			HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
			int num = 0;
			if(scanWifiList.size()>=3){
				wifiCheckVal=1;//wifi List >=3 mean wifi OK;
			}
			for (int i = 0; i < scanWifiList.size(); i++) {
				ScanResult scanResult = scanWifiList.get(i);
				if (!scanResult.SSID.isEmpty()) {
					//CheckResult = "[WIFI"+i+"]        "+scanResult.SSID;
					int resultWifiDbm=scanResult.level;
					CheckResult = formatString("[WIFI"+num+":"+resultWifiDbm+"dBm]",scanResult.SSID," ");
					mDatas.add(CheckResult);
					num ++;
				}
				if (num >= 3) {
					break;
				}
			}
			for (int j = num; j < 3; j++) {
				mDatas.add("");
			}
		} else {
			mDatas.add("");
			mDatas.add("");
			mDatas.add("");
                  wifiManager.startScan();
                }

	}

	private void BTCheck(){
		mBtManager = BTManager.getInstance(mContext);
		mBluetoothAdapter = mBtManager.mBTAdapter;

		if (mBtManager.BTData.size() > 0) {
			if(mBtManager.BTData.size()>=1){
				btCheckVal=1;//BTData>=1 mean bt is ok;
			}
			for (int i = 0; i < mBtManager.BTData.size() && i<3; i++) {
				mDatas.add(formatString("[BT" + i + "]" ,
							 mBtManager.BTData.get(i)," "));
			}
			
		}
		String CheckResult = null;

		if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
			mBluetoothAdapter.enable();
		}

		mBtManager.setHandler(btHandler);
		mBtManager.registerBTReceiver();

		startSearch();
		
	}

	private void KeystatusCheck(){
		// mDatas.add("MAC                                "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 	                Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_MAC));
		// mDatas.add("DEVICEID                         "+ MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_DEVICEID));
		// mDatas.add("HDCPKEY14                    " + MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_HDCPKEY14)
		// 			+ "      " + "WIDEVINE                       "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_WIDEVINE));
		// mDatas.add("KEYMASTER                    "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_KEYMASTER)
		// 			+ "      " + "PLAYREADY                      "+ MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY));
		// mDatas.add("PLAYREADY1                    " + MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_PLAYREADY_1)
		// 			+ "      " + "PLAYREADY2                    " + MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_PLAYREADY_2));
		// mDatas.add("PLAYREADY25                 "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY25)
		// 			+ "      " + "PLAYREADY25_1                  " + MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_PLAYREADY25_1));
		// mDatas.add("PLAYREADY25_2                  " + MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_PLAYREADY25_2)
		// 			+ "      " + "HASHKEY                        "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HASHKEY));
		// mDatas.add("HDCPKEY2                       "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HDCPKEY2)
		// 			+ "     " + "NETFLIX                            "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_NETFLIX));
		// mDatas.add("NETFLIX_ESN                        "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_NETFLIX_ESN_KEY)
		// 			+ "     " + "CI                                       "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_CI));
		// mDatas.add("CA                                       "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 					Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_CAKEY)
		// 			+ "     " + "TVWORKTIME                    "+MtkTvFApiInformation.getInstance().getIniParameter(
		// 				Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_TVWORKTIME));
		names=new String[]{"MAC","DEVICEID","HDCPKEY14","WIDEVINE","KEYMASTER","PLAYREADY"
					,"PLAYREADY1","PLAYREADY2",
					"HASHKEY","HDCPKEY2","NETFLIX","CI","CA","TVWORKTIME","MODELGROUP"};
		String mac = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_MAC);
		String deviceid = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_DEVICEID);
		String hdcpkey14 =  MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH,Contants.KEYSTATUS_HDCPKEY14);
		String widevine = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_WIDEVINE);
		String keymaster = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_KEYMASTER);
		String playready = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY);
		String playready1 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY_1);
		String playready2 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY_2);
		//String playready25 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY25);
		//String playready25_1 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY25_1);
		//String playready25_2 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_PLAYREADY25_2);
		String hashkey = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HASHKEY);
		String hdcpkey2 = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HDCPKEY2);
		String netflix = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_NETFLIX);
		//String netflix_esn = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_NETFLIX_ESN_KEY);
		String ci = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_CI);
		String ca = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_CAKEY);
		String tvworktime = MtkTvFApiInformation.getInstance().getIniParameter(Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_TVWORKTIME);
		String modelgroup=SystemProperties.get("ro.vendor.nrdp.modelgroup", "");
		//String esnid = factorySetting.getEsnId(Contants.KEY_PATH_NETFLIX_ESN_KEY);
		values=new Object[]{mac,deviceid,hdcpkey14,widevine,keymaster,playready,
			playready1,playready2,
			hashkey,hdcpkey2,netflix,ci,ca,tvworktime,modelgroup};
		for(int i=0;i<values.length;i++){
			if(values[i]==null||values.length==0){
				values[i]="NG";
			}
		}

		if(values[13].equals("NG")){
			//turn tvworktime to N/A
			values[13]="N/A";
		}

		for(int i=0;i<names.length;i++){
			Map<String,Object> showitem=new HashMap<String,Object>();
			showitem.put("names", names[i]);
			showitem.put("values", values[i]);
			listitem.add(showitem);
		}
	}

	private void startSearch() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				Log.i(TAG, "startDiscovery");
				// TODO ?????????
				if (mBluetoothAdapter != null) {
					mBluetoothAdapter.startDiscovery();
				}
			}
		}).start();
	}

	Handler btHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch (what) {
			case BTManager.MSG_BT_DEVICE_FOUND:
				BluetoothDevice device = (BluetoothDevice) msg.obj;
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					// ???TextView?

					// addSearchBluetoothDevice(device);
					Log.i(TAG, "found==" + ":" + device.getAddress() + "\n");
					Log.i(TAG, "btname==" + ":" + device.getName() + "\n");
				}
				if (device == null || device.getName() == null) {
					break;
				}

				if (!device.getName().equalsIgnoreCase("null")
						&& !device.getName().equalsIgnoreCase(lastDeviceName)
						&& !device.getName().equalsIgnoreCase(
								lastLastDeviceName)) {
					lastLastDeviceName = lastDeviceName;
					lastDeviceName = device.getName();
					if (!mBtManager.BTData.contains(device.getName()) && mBtManager.BTData.size()<3){
							mBtManager.BTData.add(device.getName());
							mDatas.add(formatString("[BT" + bt_count + "]" ,
							device.getName()," "));
					}
					adapter.notifyDataSetChanged();
					bt_count++;
				}
				if (bt_count >= 3 || mBtManager.BTData.size() >= 3) {
					mBluetoothAdapter.cancelDiscovery();
				}

				break;
			case BTManager.MSG_BT_DISCOVERY_STARTED:
				Log.d(TAG, "========DISCOVERY_STARTED========");
				// mScanState.setText(mContext.getResources().getString(
				// R.string.network_scanning));
				// mSearchBluetoothDeviceStates.clear();
				break;
			case BTManager.MSG_BT_DISCOVERY_FINISHED:
				// mScanState.setText("");
				if(mBtManager.BTData.size()>=1){
					btCheckVal=1;//BTData>=1 mean bt is ok;
				}
				showCheckResult();
				Log.d(TAG, "========DISCOVERY_FINISHED========");

				break;
			case BTManager.MSG_BT_STATE_BONDNONE:
				Log.d(TAG, "=======bond=fail==========");
				BluetoothDevice device5 = (BluetoothDevice) msg.obj;
				int error = msg.arg1;

				// if (error == BluetoothDevice.BOND_SUCCESS) {
				// removePairedBluetoothDevice(device5);
				// } else if (error ==
				// BluetoothDevice.UNBOND_REASON_AUTH_FAILED) {
				// showMessage(1);
				// } else {
				// showMessage(0);
				// }
				// updataSearchBluetoothDeviceList();
				break;
			case BTManager.MSG_BT_STATE_BONDED:
				Log.d(TAG, "=======bond=bonded==========");
				// getPairedBluetoothDevice();
				// BluetoothDevice device4 = (BluetoothDevice) msg.obj;
				// removeSearchBluetoothDevice(device4);

				break;

			case BTManager.MSG_BT_STATE_BONDING:
				Log.d(TAG, "=======bond=bonding==========");
				// updataSearchBluetoothDeviceList();
				break;
			case BTManager.MSG_BT_STATE_CONNECTED:
				// getPairedBluetoothDevice();
				break;
			case BTManager.MSG_BT_STATE_DISCONNECTED:
				// getPairedBluetoothDevice();
				break;
			case BTManager.MSG_BT_STATE_PAIRING_PASSKEYORPIN:
				Log.d(TAG, "=======pairing==with=key=or=pin===");
				int type = msg.arg1;
				int pairingKey = msg.arg2;
				BluetoothDevice device1 = (BluetoothDevice) msg.obj;
				String mPairingKey = "";
				/*//zcj 2018-10-31if (type == BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY) {
					mPairingKey = String.format("%06d", pairingKey);
				} else {
					mPairingKey = String.format("%04d", pairingKey);
				}*/
				// showPairedDialog(type, mPairingKey, device1);

				break;

			case BTManager.MSG_BT_STATE_PAIRING_CONFIRM:
				Log.d(TAG, "=======pairing11=====");
				int type1 = msg.arg1;
				int pairingKey1 = msg.arg2;
				BluetoothDevice device2 = (BluetoothDevice) msg.obj;
				String mPairingKey1 = String.format(Locale.US, "%06d",
						pairingKey1);
				// showPairedDialog(type1, mPairingKey1, device2);
				break;
			case BTManager.MSG_BT_STATE_PAIRING_VARIANT_PIN:
				Log.d(TAG, "=======pairing22=====");
				int type2 = msg.arg1;
				BluetoothDevice device3 = (BluetoothDevice) msg.obj;
				// showPairedDialog(type2, "", device3);
				break;

			default:
				break;
			}
		}
	};

	// private void initBarCode(){
	// Log.v("tv" ,"initBarCode");
	// int pidStatus =0;
	// factoryBarCodeStr =factory.getPID();
	// pidStatus =factory.getPIDStatus();
	//
	// if(pidStatus==2) {
	// if(factoryBarCodeStr.length()>=24){
	// factoryBarCodeStr = factoryBarCodeStr.substring(0,24);
	// }
	// barCodeTextViewValue.setTextColor(R.color.black);
	// barCodeTextViewPresentationText.setTextColor(R.color.black);
	// barCodeTextViewPid.setTextColor(R.color.black);
	// barCodeTextViewValue.setText(factoryBarCodeStr);
	// barCodeTextViewPresentationText.setText("ERROR");
	//
	// }else if(pidStatus==0){
	// if(factoryBarCodeStr.length()>=24){
	// factoryBarCodeStr = factoryBarCodeStr.substring(0,24);
	// }
	// barCodeTextViewValue.setTextColor(R.color.black);
	// barCodeTextViewPid.setTextColor(R.color.black);
	// barCodeTextViewPresentationText.setTextColor(R.color.black);
	// barCodeTextViewValue.setText(factoryBarCodeStr);
	// barCodeTextViewPresentationText.setText("OK");
	// }else {
	// barCodeTextViewValue.setTextColor(R.color.black);
	// barCodeTextViewPid.setTextColor(R.color.black);
	// barCodeTextViewPresentationText.setTextColor(R.color.black);
	// barCodeTextViewPresentationText.setText("NO PID");
	// }
	// factoryBarCodeStr ="";
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		Log.i(TAG, "ON finish");
		//zcj 2018-10-31 mNetworkSettingUtils.unregisterWifiStatusChangedReceiver();
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
		}
		if (mBtManager != null) {
			mBtManager.unregisterBTReceiver();
		}
		unregisterReceiver(receiver);
		super.finish();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.i(TAG, "ON PAUSE");
		// zcj add fix error 2017-6-16
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
		}
		// mBtManager.unregisterBTReceiver();
		super.onPause();
	}
        
	private class MyAdapter extends BaseAdapter{

		private Context mContext;
		private ArrayList<String> mList = null;
		private final LayoutInflater mListContainer;
		public MyAdapter(Context context, ArrayList<String> list) {
			mContext = context;
			mListContainer = LayoutInflater.from(mContext);
			mList = list;
		}
		@Override
		public long getItemId(int i) {
			return i;
		}
                @Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mList.get(position);
		}
                @Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String str =(String)getItem(position);
		        convertView = mListContainer.inflate(R.layout.simple_list_item_1, null);
                        TextView tv = (TextView)convertView.findViewById(R.id.tv_text);
                        TextView tv_ret = (TextView)convertView.findViewById(R.id.tv_text_ret);
                        Log.d(TAG,"tv = "+tv + " convertView "+convertView);

                        if(str.startsWith("USB") ){
                            if(usbCount > 0){
                            tv.setTextColor(Color.GREEN);
                            tv_ret.setTextColor(Color.GREEN);
                            tv_ret.setText(usbCount+" OK");
                            } else {
                            tv.setTextColor(Color.BLACK);
                            tv_ret.setTextColor(Color.BLACK);
                            tv_ret.setText(usbCount +" FAIL");
                            }
                            //tv.setBackgroundColor(Color.parseColor("#13C2C2"));;
                        } else if( str.startsWith("Ethernet") || str.startsWith("IP") || (str.startsWith("MAC") && str.contains(":"))){
				if( str.startsWith("Ethernet") ){
					if(factorySetting.isLanConnected()){
				            tv_ret.setTextColor(Color.GREEN);
					    tv_ret.setText("OK");
					    tv.setTextColor(Color.GREEN);
					} else {
					    tv_ret.setTextColor(Color.BLACK);
					    tv_ret.setText("FAIL");
					    tv.setTextColor(Color.BLACK);
					}
				}
                            //tv.setBackgroundColor(Color.parseColor("#1890FF"));;
                            
                        } else if(str.startsWith("[WIFI")){
                        	int rssiLv= Integer.parseInt(str.substring(str.indexOf(":")+1,str.indexOf("dBm")));
							int resultWifiLv=calculatesignalLevel(rssiLv,3);
							Log.d(TAG,resultWifiLv+"");
							switch (resultWifiLv){
								case 0:
									tv.setTextColor(Color.RED);
									break;
								case 1:
									tv.setTextColor(Color.YELLOW);
									break;
								case 2:
									tv.setTextColor(Color.GREEN);
									break;
							}
                            tv_ret.setTextColor(Color.YELLOW);
                            tv_ret.setText("OK");
                            //tv.setBackgroundColor(Color.parseColor("#13C2C2"));;
                        } else if(str.startsWith("[BT")){
                            tv.setTextColor(Color.YELLOW);
                            tv_ret.setTextColor(Color.YELLOW);
                            tv_ret.setText("OK");
                            //tv.setBackgroundColor(Color.parseColor("#1890FF"));;
                        }else if (str.endsWith("NG")) {
				 tv.setTextColor(Color.RED);
			    }else if (str.endsWith("OK") || str.startsWith("DEVICEID") || (str.startsWith("CI") && str.endsWith("0")) || str.endsWith("PRESET")) {
				 tv.setTextColor(Color.GREEN);
			    }else if (str.startsWith("TVWORKTIME")) {
				 tv.setTextColor(Color.WHITE);
			    }else {
			    tv.setTextColor(Color.BLACK);
		            //tv.setBackgroundColor(Color.YELLOW);;
                        }
//                        tv.setTextColor(Color.GREEN);
//                        tv.setBackgroundColor(Color.parseColor("#13C2C2"));;
			tv.setText(str);
                        
                    
			return convertView;
		}
                
	}
	private BroadcastReceiver receiver= new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
                                String CheckResult;
				if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
		                        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
					List<ScanResult> scanWifiList = wifiManager.getScanResults();
					if (scanWifiList != null && scanWifiList.size() > 0) {
                        int num = 0;
						HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
						for (int i = 0; i < scanWifiList.size(); i++) {
							ScanResult scanResult = scanWifiList.get(i);
							if ((!scanResult.SSID.isEmpty())&& i < 3) {
								int resultWifiDbm=scanResult.level;
								CheckResult = formatString("[WIFI"+num+":"+resultWifiDbm+"dBm]",scanResult.SSID," ");
								if (mDatas.size() <= (num + 5)) {
									mDatas.add(CheckResult);
								} else {
									mDatas.set(num + 5, CheckResult);
								}
								num ++;
							}
						}
					}
				}
                          }
			};

        private String formatString(String title, String detail, String ret){
        	String mdetail=detail;
        	if(!TextUtils.isEmpty(detail)) {
				if (detail.length() > 22) {
					mdetail = detail.substring(0, 19) + "...";
				}
			}
            String result = String.format("%-20s",title)+String.format("%-35s", mdetail) + String.format("%6s",ret) ;
			Log.d("FactoryListInfo",result);
            return result;
        }
        
        private void showVerTime(){
            String datestr = factorySetting.getSWDate();
            int index = datestr.indexOf(":");
            datestr = datestr.substring(index-2,index+6);
            Intent intent = new Intent();
                intent.setAction("com.homwee.stateservice.setkey");
                intent.putExtra("text", datestr);
                intent.putExtra("color",Color.GREEN);
                mContext.sendBroadcast(intent);

        }

        private void showCheckResult(){
			String checkResult="";
			Intent intent = new Intent();
			intent.setAction("com.homwee.stateservice.setkey");
        	if(wifiCheckVal==1&&btCheckVal==1){
				checkResult="BT&WIFI OK";
				intent.putExtra("color",Color.GREEN);
			}else if(wifiCheckVal==0&&btCheckVal==1){
        		checkResult="WIFI NG";
				intent.putExtra("color",Color.RED);
			}else if(wifiCheckVal==1&&btCheckVal==0){
        		checkResult="BT NG";
				intent.putExtra("color",Color.RED);
			}else{
        		checkResult="NG";
				intent.putExtra("color",Color.RED);
			}
			intent.putExtra("text", checkResult);
			mContext.sendBroadcast(intent);
		}

	private void EepromStatusShow() {

		String hdcp14Str = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_HDCP14);
		String hdcp2Str = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_HDCP2);
		String macStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_MAC)+"("+readMACString+")";
		String widevineStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_WIDEVINE);
		//String playready = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_PLAYREADY30_BGROUPCERT);
		//str6 = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_PLAYREADY30_ZGPRIV);
		String netflix50_kpekphStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_NETFLIX50_KPEKPH);
		String netflix50_esnidStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_NETFLIX50_ESNID);
		//String hashkeyStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_HASHKEY);
		String projectIdStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_PROJECT_ID)+"("+readPid+")";
		String deviceIdStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_DEVICE_ID);
		String ciStr = readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey.E_EepromKey_CIPLUS);

		String[] keyType = new String[]{"HDCP14", "HDCP2", "MAC", "WIDEVINE", "NETFLIX50_KPEKPH", "NETFLIX50_ESNID", "PROJECT_ID",
				"DEVICE_ID", "CIPLUS"};
		String[] keyRet =new String[]{hdcp14Str,hdcp2Str,macStr,widevineStr,netflix50_kpekphStr,netflix50_esnidStr,projectIdStr,
				deviceIdStr,ciStr};

		for(int i=0;i<keyType.length;i++){
			Map<String,Object> showitem=new HashMap<String,Object>();
			showitem.put("names", keyType[i]);
			showitem.put("values", keyRet[i]);
			listitem.add(showitem);
		}

	}


	public int calculatesignalLevel(int rssi, int numLevels) {
			int MIN_RSSI =-100;
			int MAX_RSSI =-55;
			int levels=numLevels;
			if (rssi <= MIN_RSSI) {
				return 0;
			}else if (rssi >= MAX_RSSI) {
				return levels - 1;
			}else{
				float inputRange = (MAX_RSSI - MIN_RSSI);
				float outputRange = (levels - 1);
				return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
			}
		}

	public String readKeyFromEEPROM(FactoryKeyReciver.EnumEepromKey keyType){

		String hardware= Build.HARDWARE;
		Log.d(TAG, "KEY_EEPROM_PATH:"+KEY_EEPROM_PATH);

		int[] keyStartAddress= new int[FactoryKeyReciver.EnumEepromKey.values().length];
		int[] keyEndAddress= new int[FactoryKeyReciver.EnumEepromKey.values().length];
		String[] keyNames=new String[FactoryKeyReciver.EnumEepromKey.values().length];
		int actual = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_FAIL;
		int expected = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK;
		int ret = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK;
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_HDCP14.ordinal()] = "HDCP14";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_HDCP2.ordinal()] = "HDCP2";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_MAC.ordinal()] = "MAC";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_WIDEVINE.ordinal()] = "WIDEVINE";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_PLAYREADY30_BGROUPCERT.ordinal()] = "PLAYREADY30_BGROUPCERT";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_PLAYREADY30_ZGPRIV.ordinal()] = "PLAYREADY30_ZGPRIV";
		//keyNames[EnumEepromKey.E_EepromKey_KEYMASTER.ordinal()]                               = "KEYMASTER"
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_DEVICE_ID.ordinal()] = "DEVICE_ID";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_NETFLIX50_KPEKPH.ordinal()] = "NETFLIX50_KPEKPH";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_NETFLIX50_ESNID.ordinal()] = "NETFLIX50_ESNID";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_HASHKEY.ordinal()] = "HASH_KEY";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_PROJECT_ID.ordinal()] = "PROJECT_ID";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_MMODE.ordinal()] = "MMODE";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_AGINGMODE.ordinal()] = "AGINGMODE";
		keyNames[FactoryKeyReciver.EnumEepromKey.E_EepromKey_CIPLUS.ordinal()]="CIPLUS";

		for (FactoryKeyReciver.EnumEepromKey Type : FactoryKeyReciver.EnumEepromKey.values()) {
			String startAddressKey = "EEPROM_KEY_SETTING:" + keyNames[Type.ordinal()] + "_START_ADDRESS";
			String endAddressKey = "EEPROM_KEY_SETTING:" + keyNames[Type.ordinal()] + "_END_ADDRESS";

			String startAddressStrData = MtkTvFApiInformationWrapper.getInstance().getIniParameter(KEY_EEPROM_PATH, startAddressKey);
			String endAddressStrData = MtkTvFApiInformationWrapper.getInstance().getIniParameter(KEY_EEPROM_PATH, endAddressKey);

			Log.d(TAG, startAddressKey + "=" + startAddressStrData + ", " + endAddressKey + "=" + endAddressStrData);
			if ((!startAddressStrData.equals("")) && (!endAddressStrData.equals(""))) {
				keyStartAddress[Type.ordinal()] = Integer.decode(startAddressStrData);
				keyEndAddress[Type.ordinal()] = Integer.decode(endAddressStrData);


			}
		}
		IicDevice iicdevice =IicDevice.BOARD_I2C_DEVICE_9;
		int readPos = keyStartAddress[keyType.ordinal()];

		//Relative to EEPROM spec
		//ie:in this case, address is 0x0020. addr1: 0x00, addr2:0x20
		byte addr2 = (byte) (readPos & 0x00FF);
		byte addr1 = (byte) ((readPos & 0xFF00) >> 8);
		short size = (short) (keyEndAddress[keyType.ordinal()] - keyStartAddress[keyType.ordinal()] + 1);


		ArrayList<Byte> iicAddr = new ArrayList<Byte>();
		iicAddr.add(addr1);
		iicAddr.add(addr2);

		ArrayList<Byte> getBackData = new ArrayList<Byte>();

		{
			actual = MtkTvFApiPeripheral.getInstance().readFromIic(iicdevice, MtkTvFApiIicReadMode.E_MTK_FAPI_IIC_READ_MODE_DEFAULT, iicAddr, size, getBackData);
			ret |= actual;
		}
		//Log.d(TAG, "readFromIic size: " + getBackData.size());
		if (keyType == FactoryKeyReciver.EnumEepromKey.E_EepromKey_MAC) {
			StringBuilder sb_mac = new StringBuilder();
			for (int i = 0; i < getBackData.size(); i++) {
				sb_mac.append(String.format("%02X%s", getBackData.get(i), (i < getBackData.size() - 1) ? ":" : ""));
			}
			Log.d(TAG, "Get the MAC address : " + sb_mac.toString());
			readMACString=sb_mac.toString();
		}

		if(keyType == FactoryKeyReciver.EnumEepromKey.E_EepromKey_PROJECT_ID){
			byte value1=getBackData.get(0);//eeprom address 0x1ff1
			byte value2=getBackData.get(1);//eeprom address 0x1ff2
			int combinedValue = ((value2 & 0xFF) << 8) | (value1 & 0xFF);

			Log.d(TAG, "Get the pid : " + combinedValue);
			readPid=combinedValue+"";
		}

		int count1=0;
		int count2=0;
		for(int i=0;i<getBackData.size();i++){
			if(getBackData.get(i)==0){
				count1++;
			}else if(getBackData.get(i)==-1){
				count2++;
			}
		}
		if((count1 == getBackData.size())||(count2 == getBackData.size())){
			return "NG";
		}else{
			return "OK";
		}


	}

      
        
}
